//
//  ImageUploadViewController.m
//  阿帕
//
//  Created 阿帕 on 2019/12/25.
//  Copyright © 2019 GCY. All rights reserved.
//

#import "ImageUploadViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#import "TZImagePickerController.h"
#import <WebKit/WebKit.h>
@interface ImageUploadViewController ()<TZImagePickerControllerDelegate,AMapLocationManagerDelegate,UIDocumentInteractionControllerDelegate>
{
    NSString *_exampleUrlString;
    NSString *_imageUrlString;
    NSString *_latitudeLongitudeString;
    
}
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UIButton *uploadButton;
@property (weak, nonatomic) IBOutlet UIButton *downButton;
@property (nonatomic, strong) AMapLocationManager *locationManager;

@property (nonatomic, strong) UIImagePickerController *imagePickerController;

@property (nonatomic,strong)UIDocumentInteractionController *documentInteractionController;
@end

@implementation ImageUploadViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    UIImage *bgImage = [[UIImage imageWithColor:UIColor.whiteColor] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0) resizingMode:UIImageResizingModeStretch];
    [DCSpeedy changeNavControllerGradientView:self andBgColor:bgImage andTitleColor:[UIColor blackColor]];
    
    _exampleUrlString = @"";
    _imageView.image = image(@"gcy_icon_add_photo");
    [self defaultImageHandeler:[UIImageView new]];
    
    
    
    if ([DCSpeedy isBlankString:_imageNetUrl] == NO) {
        setNetImage(_imageView, _imageNetUrl, @"gcy_icon_plaholder");
        _imageUrlString = _imageNetUrl;
        if (_imageType == 17) {
            [_downButton setHidden:NO];
            [self pdfReadAction];
        }
        else
        {
            [_downButton setHidden:YES];
        }
        
    } else {
        [_downButton setHidden:YES];
        [_uploadButton setTitle:@"上传图片" forState:UIControlStateNormal];
        
        [self defaultImageHandeler:_imageView];
    }
    
    cut(_uploadButton, BTN_BORDER_RADIUS);
    cut(_downButton, BTN_BORDER_RADIUS);
    [_uploadButton setBackgroundColor:Theme_ColorValue];
    if (_isHiddenBtn) {
        _uploadButton.hidden = YES;
    }
    
    if (!_isHiddenBtn) {
        _uploadButton.hidden = NO;
        [_imageView nyl_addTapGes:^{
            
            //MARK: - 06.点击图片调起弹窗并检查权限;
            //        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            //
            //        UIAlertAction *camera = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //            [weakSelf checkCameraPermission];//调用检查相机权限方法
            //        }];
            //        UIAlertAction *album = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //            [weakSelf checkAlbumPermission];//调起检查相册权限方法
            //        }];
            //        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {
            //            [weakSelf dismissViewControllerAnimated:YES completion:nil];
            //        }];
            //
            //        [alert addAction:camera];
            //        [alert addAction:album];
            //        [alert addAction:cancel];
            //
            //        [self presentViewController:alert animated:YES completion:nil];
            
            
        }];
    }
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    _latitudeLongitudeString = @"";
    
    self.navigationItem.title = @"图片上传";
    
    [self configLocationManager];
    
    DebugLog(@"fpwEncryString=%@", _fpwEncryString);
}

- (void)defaultImageHandeler:(UIImageView *)imageView {
    
    /**
     0 驾驶证
     1 从业资格证
     2 身份证正面
     3 身份证反面
     4 司机照
     5 行驶证
     6 道路运输证
     7 车头正面照
     8 挂车行驶证
     9 挂车运营证
     10 营业执照
     11 手持身份证
     12 挂车照片
     13 道路经营许可证
     14 车辆照
     15安全责任险
     16挂靠协议
     17车主声明
     18行驶证副页照
     19挂车行驶证副页
     
     0720需求新增
     20车辆行驶证副页背面照片
     21挂车车辆行驶证副页背面照片
     22道路运输证副页照片
     23挂车道路运输证副页照片
     24 挂车道路运输证到期日期照片未上传
     */
    
    if (_imageType == 0) {
        
        [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@/ntocc-basic-api/preview/type/driverLicenseImg", BasicDomainURL) withParameter:nil withVC:self netName:@"驾驶证" success:^(id response, NSString *msg) {
            setNetImage(imageView, response[@"img"], @"gcy_icon_plaholder");
            _exampleUrlString = response[@"img"];
        } failure:^(NSInteger code, NSString *msg) {
            imageView.image = image(@"gcy_auth_guakaoxieyi");
        }];
    } else if (_imageType == 1) {
        
        [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@/ntocc-basic-api/preview/type/workLicenseImg", BasicDomainURL) withParameter:nil withVC:self netName:@"从业资格证" success:^(id response, NSString *msg) {
            setNetImage(imageView, response[@"img"], @"gcy_icon_plaholder");
            _exampleUrlString = response[@"img"];
        } failure:^(NSInteger code, NSString *msg) {
            imageView.image = image(@"gcy_auth_guakaoxieyi");
        }];
    } else if (_imageType == 2) {
        [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@/ntocc-basic-api/preview/type/identificationImg", BasicDomainURL) withParameter:nil withVC:self netName:@"身份证正面" success:^(id response, NSString *msg) {
            setNetImage(imageView, response[@"img"], @"gcy_icon_plaholder");
            _exampleUrlString = response[@"img"];
        } failure:^(NSInteger code, NSString *msg) {
            imageView.image = image(@"gcy_auth_guakaoxieyi");
        }];
    } else if (_imageType == 3) {
        [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@/ntocc-basic-api/preview/type/identificationBack_img", BasicDomainURL) withParameter:nil withVC:self netName:@"身份证反面" success:^(id response, NSString *msg) {
            setNetImage(imageView, response[@"img"], @"gcy_icon_plaholder");
            _exampleUrlString = response[@"img"];
        } failure:^(NSInteger code, NSString *msg) {
            imageView.image = image(@"gcy_auth_guakaoxieyi");
        }];
    } else if (_imageType == 4) {
        [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@/ntocc-basic-api/preview/type/driverImg", BasicDomainURL) withParameter:nil withVC:self netName:@"司机照" success:^(id response, NSString *msg) {
            setNetImage(imageView, response[@"img"], @"gcy_icon_plaholder");
            _exampleUrlString = response[@"img"];
        } failure:^(NSInteger code, NSString *msg) {
            imageView.image = image(@"gcy_auth_guakaoxieyi");
        }];
    } else if (_imageType == 5) {
        [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@/ntocc-basic-api/preview/type/vehicleLicenseImg", BasicDomainURL) withParameter:nil withVC:self netName:@"行驶证" success:^(id response, NSString *msg) {
            setNetImage(imageView, response[@"img"], @"gcy_icon_plaholder");
            _exampleUrlString = response[@"img"];
        } failure:^(NSInteger code, NSString *msg) {
            imageView.image = image(@"gcy_auth_guakaoxieyi");
        }];
    } else if (_imageType == 6) {
        [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@/ntocc-basic-api/preview/type/roadTransportCertificateImg", BasicDomainURL) withParameter:nil withVC:self netName:@"道路运输证" success:^(id response, NSString *msg) {
            setNetImage(imageView, response[@"img"], @"gcy_icon_plaholder");
            _exampleUrlString = response[@"img"];
        } failure:^(NSInteger code, NSString *msg) {
            imageView.image = image(@"gcy_auth_guakaoxieyi");
        }];
    } else if (_imageType == 7) {
        [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@/ntocc-basic-api/preview/type/vehicleImg", BasicDomainURL) withParameter:nil withVC:self netName:@"车头正面照" success:^(id response, NSString *msg) {
            setNetImage(imageView, response[@"img"], @"gcy_icon_plaholder");
            _exampleUrlString = response[@"img"];
        } failure:^(NSInteger code, NSString *msg) {
            imageView.image = image(@"gcy_auth_guakaoxieyi");
        }];
    } else if (_imageType == 8) {
        [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@/ntocc-basic-api/preview/type/trailerVehicleLicenseImg", BasicDomainURL) withParameter:nil withVC:self netName:@"挂车行驶证" success:^(id response, NSString *msg) {
            setNetImage(imageView, response[@"img"], @"gcy_icon_plaholder");
            _exampleUrlString = response[@"img"];
        } failure:^(NSInteger code, NSString *msg) {
            imageView.image = image(@"gcy_auth_guakaoxieyi");
        }];
    } else if (_imageType == 9) {
        [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@/ntocc-basic-api/preview/type/trailerRoadTransportCertificateImg", BasicDomainURL) withParameter:nil withVC:self netName:@"挂车运营证" success:^(id response, NSString *msg) {
            setNetImage(imageView, response[@"img"], @"gcy_icon_plaholder");
            _exampleUrlString = response[@"img"];
        } failure:^(NSInteger code, NSString *msg) {
            imageView.image = image(@"gcy_auth_guakaoxieyi");
        }];
    } else if (_imageType == 10) {
        [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@/ntocc-basic-api/preview/type/businessLicenseImg", BasicDomainURL) withParameter:nil withVC:self netName:@"营业执照" success:^(id response, NSString *msg) {
            setNetImage(imageView, response[@"img"], @"gcy_icon_plaholder");
            _exampleUrlString = response[@"img"];
        } failure:^(NSInteger code, NSString *msg) {
            imageView.image = image(@"gcy_auth_guakaoxieyi");
        }];
    } else if (_imageType == 11) {
        [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@/ntocc-basic-api/preview/type/identificationInhandImg", BasicDomainURL) withParameter:nil withVC:self netName:@"手持身份证" success:^(id response, NSString *msg) {
            setNetImage(imageView, response[@"img"], @"gcy_icon_plaholder");
            _exampleUrlString = response[@"img"];
        } failure:^(NSInteger code, NSString *msg) {
            imageView.image = image(@"gcy_auth_guakaoxieyi");
        }];
    } else if (_imageType == 12) {
        [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@/ntocc-basic-api/preview/type/trailerVehicleImg", BasicDomainURL) withParameter:nil withVC:self netName:@"挂车照片" success:^(id response, NSString *msg) {
            setNetImage(imageView, response[@"img"], @"gcy_icon_plaholder");
            _exampleUrlString = response[@"img"];
        } failure:^(NSInteger code, NSString *msg) {
            imageView.image = image(@"gcy_auth_guakaoxieyi");
        }];
    } else if (_imageType == 13) {
        [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@/ntocc-basic-api/preview/type/roadOperationPermit", BasicDomainURL) withParameter:nil withVC:self netName:@"道路经营许可证" success:^(id response, NSString *msg) {
            setNetImage(imageView, response[@"img"], @"gcy_icon_plaholder");
            _exampleUrlString = response[@"img"];
        } failure:^(NSInteger code, NSString *msg) {
            imageView.image = image(@"gcy_auth_guakaoxieyi");
        }];
    } else if (_imageType == 14) {
        [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@/ntocc-basic-api/preview/type/vehicleImg", BasicDomainURL) withParameter:nil withVC:self netName:@"车辆照" success:^(id response, NSString *msg) {
            setNetImage(imageView, response[@"img"], @"gcy_icon_plaholder");
            _exampleUrlString = response[@"img"];
        } failure:^(NSInteger code, NSString *msg) {
            imageView.image = image(@"gcy_auth_guakaoxieyi");
        }];
    }
    
    
    
    else if (_imageType == 15) {
        //_imageView.image = image(@"gcy_auth_anquanzeren");//10.68
        [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@/ntocc-basic-api/preview/type/safeDutyInsureImg", BasicDomainURL) withParameter:nil withVC:self netName:@"安全责任险" success:^(id response, NSString *msg) {
            setNetImage(imageView, response[@"img"], @"gcy_icon_plaholder");
            _exampleUrlString = response[@"img"];
        } failure:^(NSInteger code, NSString *msg) {
            imageView.image = image(@"gcy_auth_guakaoxieyi");
        }];
    } else if (_imageType == 16) {
        //_imageView.image = image(@"gcy_auth_guakaoxieyi.jpg");
        [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@/ntocc-basic-api/preview/type/depenDealImg", BasicDomainURL) withParameter:nil withVC:self netName:@"挂靠协议" success:^(id response, NSString *msg) {
            setNetImage(imageView, response[@"img"], @"gcy_icon_plaholder");
            _exampleUrlString = response[@"img"];
        } failure:^(NSInteger code, NSString *msg) {
            imageView.image = image(@"gcy_auth_guakaoxieyi");
        }];
    } else if (_imageType == 17) {
        [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@/ntocc-basic-api/preview/type/stateImg", BasicDomainURL) withParameter:nil withVC:self netName:@"车主声明" success:^(id response, NSString *msg) {
            setNetImage(imageView, response[@"img"], @"gcy_icon_plaholder");
            _exampleUrlString = response[@"img"];
        } failure:^(NSInteger code, NSString *msg) {
            imageView.image = image(@"gcy_auth_guakaoxieyi");
        }];
        [_downButton setHidden:NO];
        [self pdfReadAction];
    }
    else if (_imageType == 18){
        [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@/ntocc-basic-api/preview/type/vehicleLicenseDeputyPageImg", BasicDomainURL) withParameter:nil withVC:self netName:@"行驶证副页" success:^(id response, NSString *msg) {
            setNetImage(imageView, response[@"img"], @"gcy_icon_plaholder");
            _exampleUrlString = response[@"img"];
        } failure:^(NSInteger code, NSString *msg) {
            imageView.image = image(@"gcy_auth_guakaoxieyi");
        }];
    }
    else if (_imageType == 19){
        [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@/ntocc-basic-api/preview/type/trailerVehicleLicenseDeputyPageImg", BasicDomainURL) withParameter:nil withVC:self netName:@"挂车行驶证副页" success:^(id response, NSString *msg) {
            setNetImage(imageView, response[@"img"], @"gcy_icon_plaholder");
            _exampleUrlString = response[@"img"];
        } failure:^(NSInteger code, NSString *msg) {
            imageView.image = image(@"gcy_auth_guakaoxieyi");
        }];
    }
    
    
    
    else if (_imageType == 20){
        [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@/ntocc-basic-api/preview/type/vehicleLicenseDeputyPageBackImg", BasicDomainURL) withParameter:nil withVC:self netName:@"车辆行驶证副页背面照片" success:^(id response, NSString *msg) {
            setNetImage(imageView, response[@"img"], @"gcy_icon_plaholder");
            _exampleUrlString = response[@"img"];
        } failure:^(NSInteger code, NSString *msg) {
            imageView.image = image(@"gcy_auth_guakaoxieyi");
        }];
    }else if (_imageType == 21){
        [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@/ntocc-basic-api/preview/type/trailerVehicleLicenseDeputyPageBackImg", BasicDomainURL) withParameter:nil withVC:self netName:@"挂车车辆行驶证副页背面照片" success:^(id response, NSString *msg) {
            setNetImage(imageView, response[@"img"], @"gcy_icon_plaholder");
            _exampleUrlString = response[@"img"];
        } failure:^(NSInteger code, NSString *msg) {
            imageView.image = image(@"gcy_auth_guakaoxieyi");
        }];
        
    }else if (_imageType == 22){
        [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@/ntocc-basic-api/preview/type/roadTransportCertificateDeputyPageImg", BasicDomainURL) withParameter:nil withVC:self netName:@"道路运输证副页照片" success:^(id response, NSString *msg) {
            setNetImage(imageView, response[@"img"], @"gcy_icon_plaholder");
            _exampleUrlString = response[@"img"];
        } failure:^(NSInteger code, NSString *msg) {
            imageView.image = image(@"gcy_auth_guakaoxieyi");
        }];
    }else if (_imageType == 23){
        [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@/ntocc-basic-api/preview/type/trailerRoadTransportCertificateDeputyPageImg", BasicDomainURL) withParameter:nil withVC:self netName:@"挂车道路运输证副页照片" success:^(id response, NSString *msg) {
            setNetImage(imageView, response[@"img"], @"gcy_icon_plaholder");
            _exampleUrlString = response[@"img"];
        } failure:^(NSInteger code, NSString *msg) {
            imageView.image = image(@"gcy_auth_guakaoxieyi");
        }];
    }
    else {
        _imageView.image = image(@"gcy_icon_add_photo");
        
    }
    
}

- (void)pdfReadAction {
    if ([self isFileExist:@"fb1ee02ab5344501aebe86994b836a5c.pdf"]) {
        [self.downButton setTitle:@"已下载,点击分享" forState:(UIControlStateNormal)];
    } else {
        [self.downButton setTitle:@"模板文件下载" forState:(UIControlStateNormal)];
    }
        
}

- (IBAction)uploadFunClick:(UIButton *)sender {
    
    //    if ([DCSpeedy isBlankString:_imageUrlString] == YES) {
    //        [XSInfoView showInfo:@"请先上传图片" onView:self.view];
    //        return;
    //    }
    
    if ([DCSpeedy isBlankString:_imageNetUrl]) {
        
        [self pushPhotoViewEvent];
        
        return;
    }
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    //取消
    UIAlertAction *changeAction = [UIAlertAction actionWithTitle:@"更换照片" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
        
        [self pushPhotoViewEvent];
    }];
    //确定
    UIAlertAction *checkAction = [UIAlertAction actionWithTitle:@"查看大图" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
        
        HZPhotoBrowser *browser = [[HZPhotoBrowser alloc] init];
        browser.isFullWidthForLandScape = YES;
        browser.isNeedLandscape = YES;
        browser.currentImageIndex =0;
        browser.imageArray = @[_imageNetUrl];
        [browser show];
        
    }];
    
    UIAlertAction *exampleAction = [UIAlertAction actionWithTitle:@"查看示例" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
        
        HZPhotoBrowser *browser = [[HZPhotoBrowser alloc] init];
        browser.isFullWidthForLandScape = YES;
        browser.isNeedLandscape = YES;
        browser.currentImageIndex = 0;
        browser.imageArray = @[_exampleUrlString];
        [browser show];
        
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action){
        
    }];
    
    [alertController addAction:changeAction];
    [alertController addAction:checkAction];
    [alertController addAction:exampleAction];
    [alertController addAction:cancelAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)pushPhotoViewEvent {
    
    [SystemPermissionsToolObject determineLatestPermissionsOfTheLocalAlbum];
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:4 delegate:self pushPhotoPickerVc:YES];
    imagePickerVc.allowPickingVideo = NO;
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
        NSArray *imgArr = [NSArray array];
        
        ///是否加入水印（暂时废弃）
        if (_isAddWatermark) {
            //            UIImage *watermarkImage = [DCSpeedy addWatermarkToPicture:[photos firstObject] :@"" :CJStringWithFormat(@"经纬度：%@", _latitudeLongitudeString)];
            //            imgArr = @[watermarkImage];
            imgArr = photos;
        } else {
            imgArr = photos;
        }
        
        NSString *uploadUrl = @"";
        
        if ([DCSpeedy isBlankString:_fpwEncryString]) {
            uploadUrl = CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-tps-api",[ReAddressDynamic shared].baseUrl], FILE_UPLOAD);
        } else {
            uploadUrl = CJStringWithFormat(@"%@%@/%@", [NSString stringWithFormat:@"%@/ntocc-tps-api",[ReAddressDynamic shared].baseUrl], FILE_UPLOAD, _fpwEncryString);
        }
        
        [HTTPManager postUploadFiles:uploadUrl file:imgArr fileName:@"file" withVC:self netName:@"文件上传" success:^(id response, NSString *msg) {
            
//            [XSInfoView showInfo:@"上传成功" onView:self.view];
            
            if (self.delegate && [self.delegate respondsToSelector:@selector(getImageUrlSting:andImageType:)]) {
                [self.delegate getImageUrlSting: response[@"data"] andImageType:_imageType];
                
                [self.navigationController popViewControllerAnimated:YES];
            }
            
        } failure:^(NSInteger code, NSString *msg) {
            
        }];
        
    }];
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

#pragma mark - Camera(检查相机权限方法)
- (void)checkCameraPermission {
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (status == AVAuthorizationStatusNotDetermined) {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                [self takePhoto];
            }
        }];
    } else if (status == AVAuthorizationStatusDenied || status == AVAuthorizationStatusRestricted) {
        
        [self alertAlbum];//如果没有权限给出提示
    } else {
        [self takePhoto];//有权限进入调起相机方法
    }
}
- (void)takePhoto {
#pragma mark - 07.判断相机是否可用，如果可用调起
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        self.imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:self.imagePickerController animated:YES completion:^{
            
        }];
    } else {//不可用只能GG了
        NSLog(@"没有相机");
    }
}
#pragma mark - Album(相册流程与相机流程相同,相册是不存在硬件问题的,只要有权限就可以直接调用)
- (void)checkAlbumPermission {
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusNotDetermined) {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (status == PHAuthorizationStatusAuthorized) {
                    [self selectAlbum];
                }
            });
        }];
    } else if (status == PHAuthorizationStatusDenied || status == PHAuthorizationStatusRestricted) {
        [self alertAlbum];
    } else {
        [self selectAlbum];
    }
}
- (void)selectAlbum {
    //判断相册是否可用
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        self.imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:self.imagePickerController animated:YES completion:^{
            
        }];
    }
}

- (void)alertAlbum {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"请在设置中打开相册" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark - 03.懒加载初始化弹框;
- (UIImagePickerController *)imagePickerController {
    if (_imagePickerController == nil) {
        _imagePickerController = [[UIImagePickerController alloc] init];
        _imagePickerController.modalPresentationStyle = UIModalPresentationFullScreen;
        _imagePickerController.delegate = self; //delegate遵循了两个代理
        _imagePickerController.allowsEditing = NO;
    }
    return _imagePickerController;
}


- (void)configLocationManager
{
    self.locationManager = [[AMapLocationManager alloc] init];
    
    [self.locationManager setDelegate:self];
    
    //设置期望定位精度
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    
    //设置定位超时时间
    [self.locationManager setLocationTimeout:DefaultLocationTimeout];
    
    //设置逆地理超时时间
    [self.locationManager setReGeocodeTimeout:DefaultReGeocodeTimeout];
    
    //设置允许连续定位逆地理
    [self.locationManager setLocatingWithReGeocode:YES];
    
    [self.locationManager startUpdatingLocation];
}

- (void)cleanUpAction
{
    //停止定位
    [self.locationManager stopUpdatingLocation];
    
    [self.locationManager setDelegate:nil];
    
}

#pragma mark - AMapLocationManager Delegate

/**
 *  @brief 连续定位回调函数.注意：如果实现了本方法，则定位信息不会通过amapLocationManager:didUpdateLocation:方法回调。
 *  @param manager 定位 AMapLocationManager 类。
 *  @param location 定位结果。
 *  @param reGeocode 逆地理信息。
 */
- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location reGeocode:(AMapLocationReGeocode *)reGeocode
{
    NSLog(@"location:{lat:%f; lon:%f; accuracy:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
    
    _latitudeLongitudeString = CJStringWithFormat(@"%f，%f", location.coordinate.longitude, location.coordinate.latitude);
    
    [UserDefaultUtil saveValue:CJStringWithFormat(@"%f",location.coordinate.longitude) forKey:LONGITUDE];
    [UserDefaultUtil saveValue:CJStringWithFormat(@"%f",location.coordinate.latitude) forKey:LATITUDE];
    
    //详细信息
    if (reGeocode)
    {
        NSLog(@"reGeocode:%@", reGeocode);
        //        _locateAddress = reGeocode.formattedAddress;
    }
    
}

- (void)amapLocationManager:(AMapLocationManager *)manager doRequireLocationAuth:(CLLocationManager *)locationManager
{
    [locationManager requestAlwaysAuthorization];
}

/**
 *  @brief 当定位发生错误时，会调用代理的此方法。
 *  @param manager 定位 AMapLocationManager 类。
 *  @param error 返回的错误，参考 CLError 。
 */
- (void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error {
    
    DebugLog(@"定位error：%@",error);
}
- (void)dealloc
{
    [KNotificationCenter removeObserver:self name:@"faceIdentifySuccess" object:nil];
    [self cleanUpAction];
}

- (IBAction)downTaskAction:(id)sender {
    [self downloadPDF:@"https://laiquzhiyun.obs.cn-north-4.myhuaweicloud.com:443/2021-08-11/fb1ee02ab5344501aebe86994b836a5c.pdf"];
}
- (void)downloadPDF:(NSString *)downloadUrl{
    
    NSArray *array = [downloadUrl componentsSeparatedByString:@"/"]; //从字符/中分隔成多个元素的数组
    
    NSString *file = [array lastObject];
    
    if ([self isFileExist:file]) {
        
        //获取Documents 下的文件路径
        
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        
        NSString *path = [paths objectAtIndex:0];
        
        NSString *pathString = [path stringByAppendingFormat:@"/%@",file];
        
        NSLog(@"path:%@", pathString);
        
        [self loadDocument:pathString];
        
    }else{
        
        //从新下载
        
        [self downloadFile:downloadUrl];
        
    }
    
}
-(BOOL) isFileExist:(NSString *)fileName

{
    
    //获取Documents 下的文件路径
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *path = [paths objectAtIndex:0];
    
    NSString *filePath = [path stringByAppendingPathComponent:fileName];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL result = [fileManager fileExistsAtPath:filePath];
    
    NSLog(@"这个文件已经存在：%@",result?@"是的":@"不存在");
    
    return result;
    
}
- (void)downloadFile:(NSString *)downLoadUrl{
    
    WEAKSELF
    [SVProgressHUD showWithStatus:REQUESTLOADING_MESSAGE];
    //设置HUD的Style
    [SVProgressHUD setDefaultStyle:(SVProgressHUDStyleDark)];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    //设置HUD和文本的颜色
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
    //设置HUD背景颜色
    [SVProgressHUD setBackgroundColor:RGBA(0, 0, 0, 0.7)];
    
    NSURL *URL = [NSURL URLWithString:downLoadUrl];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        NSLog(@"###%@", targetPath);  //原始文件
        NSLog(@"**%@", [response suggestedFilename]);  //文件名
        return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
        
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        NSLog(@"File downloaded to: %@", filePath);//下载成功后本地保存id以及文件路径
        //NSString *stringUrl = [filePath absoluteString];
        [SVProgressHUD dismissWithDelay:1.0];
        [self.downButton setTitle:@"已下载,点击分享" forState:(UIControlStateNormal)];
        [XSInfoView showInfo:@"下载完成" onView:weakSelf.view];
        // mPdf_dic[pdf_id] = stringUrl;
        //NSDictionary *pdfDic = [NSDictionary dictionaryWithDictionary:mPdf_dic];
        //[Tool saveLocalvalue:pdfDic key:PDFLOCAL_DIC];
        //pdfFilePath(stringUrl);
    }];
    [downloadTask resume];
    
    
}
//调用本地分享
-(void)loadDocument:(NSString *)documentName{

    
//    NSArray *array = [documentName componentsSeparatedByString:@"/"]; //从字符/中分隔成多个元素的数组
//
//    NSString *file = [array lastObject];
//    NSArray *array_temp = [file componentsSeparatedByString:@"."];
//    NSString *name = [array_temp firstObject];
//    NSString *localPath = [[NSBundle mainBundle] pathForResource:name ofType:@"pdf"];
    NSURL *pathUrl = [[NSURL alloc]initFileURLWithPath:documentName];
    
    // Initialize Document Interaction Controller
    self.documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:pathUrl];
    
    // Configure Document Interaction Controller
    [self.documentInteractionController setDelegate:self];
    
    // Present Open In Menu
    [self.documentInteractionController presentOptionsMenuFromRect:[self.downButton frame] inView:self.view animated:YES];
    
}


#pragma mark Document Interaction Controller Delegate Methods
- (UIViewController *) documentInteractionControllerViewControllerForPreview: (UIDocumentInteractionController *) controller {
    return self;
}



@end
